<?php
	class SignalReader{
		
		public $file = null;
		public $samples = null;
		public $min;
		public $max;
		public $numSamples = 0;
		
		public function __construct($file=false){
			$this->file = $file;
			$this->samples = array();
			if ($file) $this->process();
		}
		
		public function process(){
			$fp=fopen($this->file,"r");
			$i = 0;
			while(!feof($fp)){
				$sample = fgets($fp);
				if ($i > 0){
					if ($sample < $this->min) $this->min = $sample;
					if ($sample > $this->max) $this->max = $sample;
				}else{
					$this->min = $sample; //calculo el valor minimo de la señal
					$this->max = $sample; //calculo el valor maximo de la señal
				}
				$this->samples[] = $sample;
				$i++;
			}
			fclose($fp);

			$this->numSamples = count($this->samples);
		}
		
		public function calculateEdges(){
			$i = 0;
			$this->numSamples = count($this->samples);
			
			for ($i=0; $i < $this->numSamples; $i++){
				$sample = $this->samples[$i];
				
				if ($i > 0){
					if ($sample < $this->min) $this->min = $sample;
					if ($sample > $this->max) $this->max = $sample;
				}else{
					$this->min = $sample; //calculo el valor minimo de la señal
					$this->max = $sample; //calculo el valor maximo de la señal
				}
			
			}
		}
				
		public function serialize(){
			$serialized = implode("|",$this->samples);
			$serialized = str_replace(" ","",$serialized);
			$serialized = str_replace("\r","",$serialized);
			$serialized = str_replace("\n","",$serialized);
			return $serialized; // Remuevo caracteres en blanco, fin de carro y nueva linea
		}
		
		
		public function unserialize($str_samples){
			$this->samples = explode("|",$str_samples);
			$this->calculateEdges();
			return;
		}
		
		public function toJSON(){

			$reply = '{';
			$reply.= '"minimo":"'.$this->min.'",';
			$reply.= '"maximo":"'.$this->max.'",';
			$reply.= '"nsamples":"'.$this->numSamples.'",';
			
			$reply.= '"data":[';
		
			foreach($this->samples as $x=>$y){
				$reply.='["'.$x.'","'.$y.'"],';
			}
		
			$reply = substr($reply,0,-1);
			$reply.=']}';

			return $reply;
				
		}
		
	}
?>